﻿using Dapper;
using Microsoft.AspNetCore.Http;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Helpers;
using PersonalWebsite.Core.Result;

namespace PersonalWebsite.Application.Queries.Website;

public record GetAdminProExperienceVO
{
    public int Id { get; init; }
    public string ImageUrl { get; private set; }
    public string Year { get; init; }
    public string Name { get; init; }
    public string Desc { get; init; }

    public void SetInternetImageUrl(IHttpContextAccessor httpContextAccessor)
    {
        if (!string.IsNullOrEmpty(ImageUrl))
        {
            ImageUrl = FileHelper.GetProExperienceFile(httpContextAccessor, ImageUrl);
        }
    }
}

public class GetAdminProExperienceQuery : IQuery<ApiResult<List<GetAdminProExperienceVO>>, List<GetAdminProExperienceVO>>
{
}

public class GetAdminProExperienceQueryHandler : QueryHandler<GetAdminProExperienceQuery, ApiResult<List<GetAdminProExperienceVO>>, List<GetAdminProExperienceVO>>
{
    private readonly IHttpContextAccessor httpContextAccessor;
    private readonly IDBConnectionFactory dBConnectionFactory;

    public GetAdminProExperienceQueryHandler(IHttpContextAccessor httpContextAccessor, IDBConnectionFactory dBConnectionFactory):base(dBConnectionFactory)
    {
        this.httpContextAccessor = httpContextAccessor;
        this.dBConnectionFactory = dBConnectionFactory;
    }

    public override async Task<ApiResult<List<GetAdminProExperienceVO>>> Handle(GetAdminProExperienceQuery request, CancellationToken cancellationToken)
    {
        using var dbConnection = dBConnectionFactory.GetDbConnection();
        string sql = "SELECT * FROM WS_ProExperience";
        var data = await dbConnection.QueryAsync<GetAdminProExperienceVO>(sql);

        var result = new List<GetAdminProExperienceVO>();
        if (data != null && data.Any())
        {
            foreach (var item in data)
            {
                item.SetInternetImageUrl(httpContextAccessor);
                result.Add(item);
            }
        }

        return await Task.FromResult(ApiResult<List<GetAdminProExperienceVO>>.Success(result));
    }
}